package com.github.willisaway.core.threadpool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.Data;

/**
 * 线程池管理类
 * @author lishao
 *
 */
@Data
public class ThreadPoolManager {
    static Logger logger = LoggerFactory.getLogger(ThreadPoolManager.class);
    private static Map<String,ThreadPool> pools = new <String,ThreadPool> HashMap();//所有的线程池
    public static boolean printFlag=true;//打印开关，为ture则打印线程池的信息，否则不打印
    /**
     * 将任务放置到所属线程池
     * @param poolCode
     * @param thread
     */
    public static void addTask(ThreadExtend thread){
        ThreadPool pool = pools.get(thread.getPoolCode());
        if(pool==null){
            pool=new ThreadPool(thread.getNThreads());
            pool.setCode(thread.getPoolCode());
            pool.setName(thread.getPoolName());
            pools.put(thread.getPoolCode(), pool);
        }
        pool.addTask(thread);
    }
    
    public static Map<String,ThreadPool> getPools(){
        return pools;
    }
    
    public static ThreadPool getPool(String poolCode){
        return pools.get(poolCode);
    }
    
    //单个线程池是否执行完成
    public static boolean isComplete(String poolCode) {
        return isComplete(ThreadPoolManager.getPool(poolCode));
    }
    
    public static boolean isComplete(ThreadPool pool) {
        if(pool.getPool().getActiveCount()==0) {
            return true;
        }else {
            return false;
        }
    }
    //所有线程池是否执行完成
    public static boolean isComplete() {
        boolean result = true;
        Iterator it = pools.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String,ThreadPool> mapEntry=(Map.Entry<String,ThreadPool>)it.next();
            if(!isComplete(mapEntry.getValue())) {
                result = false;
                return result;
            }
        }
        return result;
    }
    /**
     * 打印线程池信息
     * @param poolCode
     */
    public static void printPoolInfo(String poolCode){
        ThreadPool pool = pools.get(poolCode);
        printPoolInfo(pool);
    }
    public static void printPoolInfo(ThreadPool pool){
        if(pool!=null){
            pool.printPoolInfo();
        }
    }
    public static void printPoolInfo(){
        if(printFlag){
            Iterator it = pools.entrySet().iterator();
            logger.info("打印线程池信息:");
            logger.info("**********************************************************************************************");
            while(it.hasNext()){
                Map.Entry<String,ThreadPool> mapEntry=(Map.Entry<String,ThreadPool>)it.next();
                printPoolInfo(mapEntry.getValue());
            }
            logger.info("**********************************************************************************************");
    	}
    }
}
